package user

import (
	"context"
	"fmt"
	"github.com/asaskevich/govalidator"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	project_common "test.com/project-common"
	"test.com/project-user/pkg/dao"
	"test.com/project-user/pkg/mode"
	"time"
)

type UserHandler struct {
	cache *dao.RedisCache
}

func New() *UserHandler {
	return &UserHandler{
		cache: dao.New(),
	}
}

func (h *UserHandler) getCaptcha(ctx *gin.Context) {
	resp := &project_common.Response{}
	req := &project_common.UserRequest{}

	err := ctx.ShouldBindJSON(req)
	if err != nil {
		ctx.JSON(http.StatusOK, resp.Fail(mode.CommonError, err.Error()))
		return
	}
	_, err = govalidator.ValidateStruct(req)
	if err != nil {
		ctx.JSON(http.StatusOK, resp.Fail(mode.NoLegalMobile, err.Error()))
		return
	}

	code := "456789"
	go func() {
		context, cancel := context.WithTimeout(context.Background(), 5*time.Second)
		defer cancel()

		err = h.cache.Put(context, "phone", req.Phone, 5*time.Minute)
		if err != nil {
			zap.L().Error("验证码存入出错, error: " + err.Error())
		}

		zap.L().Info(fmt.Sprintf("验证码存入成功, key %s , value: %s", "phone", req.Phone))
	}()

	ctx.JSON(http.StatusOK, resp.Success(code))
}
